import backtrader as bt

# 自定义指标  macd
# mmm.MACD(self.data, short=self.p.macd_short, long=self.p.macd_long, signal=self.p.macd_signal)
class MACD(bt.Indicator):
    lines = ('macd', 'signal')
    params = (('short', 12), ('long', 26), ('signal', 9))
 
    def __init__(self):
        # 快线
        self.short_ema = bt.ind.EMA(self.data.close, period=self.p.short)
        # 慢线
        self.long_ema = bt.ind.EMA(self.data.close, period=self.p.long)
        # 柱状体
        self.lines.macd = self.short_ema - self.long_ema  # MACD line
        # macd 的周期移动平均线
        self.lines.signal = bt.ind.EMA(self.lines.macd, period=self.p.signal)  # Signal line

# 自定义指标 唐奇安通道
# mmm.DonchianChannel(self.data, period=self.p.donchian_period)
class DonchianChannel(bt.Indicator):
    lines = ('upper', 'middle', 'lower')
    params = (('period', 25),)
 
    def __init__(self):
        # 上通道
        self.lines.upper = bt.indicators.Highest(self.data.high, period=self.p.period)
        # 下轨
        self.lines.lower = bt.indicators.Lowest(self.data.low, period=self.p.period)
        # 中轨
        self.lines.middle = (self.lines.upper + self.lines.lower) / 2

 
# 自定义指标 ATR
# mmm.ATR(self.data, period=self.p.atr_period)
class ATR(bt.Indicator):
    lines = ('atr',)
    params = (('period', 14),)
 
    def __init__(self):
        self.tr = bt.indicators.Max(
            self.data.high - self.data.low,
            abs(self.data.high - self.data.close[-1]),
            abs(self.data.low - self.data.close[-1])
        )
        self.lines.atr = bt.indicators.SMA(self.tr, period=self.p.period) 